<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" @open="openDialogMenu">
    <el-tree
      ref="treeRef"
      show-checkbox
      :data="treeData"
      :props="tree.props"
      node-key="id"
      :loading="treeLoading"
      :default-checked-keys="defaultExpandedKeys"
      :default-expanded-keys="[3]"
      @check-change="treeCheck"
    />
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="submit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, nextTick, getCurrentInstance, toRef } from 'vue'
import { internetApi } from '@/api/api.js'
import { arrayToTree } from '@/utils/tree.js'
import { ElMessage } from 'element-plus'

const currentInstance = getCurrentInstance()
const { $request } = currentInstance.appContext.config.globalProperties

const dialogTitle = ref('') //弹窗标题
const dialogVisible = ref(false)
const treeData = ref([])
const defaultExpandedKeys = ref([])
const menuIdList = ref([])
const treeRef = ref(null)
const treeLoading = ref(false)
const loading = ref(false)
const roleId = ref('')
const tree = {
  props: {
    children: 'children',
    label: 'name'
  }
}
const openDialogMenu = (row, type) => {
  treeLoading.value = true
  dialogVisible.value = true
  dialogTitle.value = '菜单权限'
  if (type === 'menu') {
    roleId.value = row.id
    Promise.all([getDeptList(), getRoleMenuPermission(row.id)])
  }
}
//获取菜单列表
const getDeptList = () => {
  $request(internetApi.getMenuList).then((res) => {
    treeData.value = arrayToTree(res.data, { pid: 'parentId', rootId: '0' })
    console.log('树状路由++', treeData.value)
  })
}
//获取当前角色已有的权限
const getRoleMenuPermission = (id) => {
  $request(internetApi.getRoleMenuPermission, { roleId: id }).then((res) => {
    menuIdList.value = res.data
    defaultExpandedKeys.value = res.data
    treeLoading.value = false
  })
}
// 选择菜单
const treeCheck = () => {
  menuIdList.value = treeRef.value.getCheckedKeys()
  // console.log('1--------------------------------->',menuIdList.value)
}
// 数据权限提交
const submit = () => {
  loading.value = true
  $request(internetApi.addRoleMenuPermission, {
    roleId: roleId.value,
    menuIdList: menuIdList.value
  })
    .then(() => {
      dialogVisible.value = false
      loading.value = false
      ElMessage({
        message: '操作成功',
        type: 'success'
      })
    })
    .catch(() => {
      loading.value = false
    })
}
defineExpose({
  openDialogMenu
})
</script>
<style lang="scss" scoped>
.from-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.menu-dialog {
  .el-select {
    width: 100%;
  }
}
</style>
